<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class companies extends CI_Controller {
	var $data;
	public function __construct()
	{
		parent::__construct();		
		$this->load->library('session');
		$this->load->library('pagination');
		$data['title'] = "Companies";		
		$this->load->model('model_companies');
		$this->load->model('model_customer');
		// CHECK LOGIN
		$check = $this->session->userdata('login');
		if($check==false){
			redirect(base_url().'login/', 'refresh');
			return;
		}
	}
	
	public function index()
	{

		$this->view();
	}

	public function view($paging=0){
		if($paging<0){
			$paging=0;
		}
		
			if(isset($_REQUEST["where"])&&$_REQUEST["where"]!=""){
				$where	=$_REQUEST["where"];
			}else{
				$where	='';
			}
			
			if(isset($_REQUEST["comp_type"])){
				$comp_type	=$_REQUEST["comp_type"];
			}else{
				$comp_type	='1';
			}

			if(isset($_REQUEST["comp_status"])&&$_REQUEST["comp_status"]!=""){
				$comp_status	=$_REQUEST["comp_status"];
			}else{
				$comp_status	='';
			}

			
		$this->data["set_page"] 	= 'companies_list';
		$per = $this->session->userdata('user_info');
		$my_permisstion = $per["permission_apps"]["AM_SALE_SUPPORT"];		

		$order_by="comp_status ASC,  `tbl_companies`.`comp_id` DESC";		
		if(isset($my_permisstion["user_type"]["is_account"])){
			$this->data["result"] 	= $this->model_companies->select(array("where"=>$where,"order_by"=>$order_by,"comp_type"=>$comp_type,"comp_status"=>$comp_status,'limit'=>10,'paging'=>$paging));
			$this->data["count_page"]	 = $this->model_companies->selectCount(array("where"=>$where,"comp_type"=>$comp_type,"comp_status"=>$comp_status));
		}else{
			
		

			
			//$comp_status=$_POST["comp_status"];

			$array_parent_id = $this->session->userdata('parentId');
			//echo "test";
			//PRINT_R($array_parent_id);
			$this->data["result"] 		= $this->model_companies->select(array("where"=>$where,"order_by"=>$order_by,"comp_type"=>$comp_type,"comp_status"=>$comp_status,"cust_creator_id"=>$this->session->userdata('uId'),"array_uId"=>$array_parent_id,'limit'=>10,'paging'=>$paging));
			$this->data["count_page"]	 = $this->model_companies->selectCount(array("where"=>$where,"comp_type"=>$comp_type,"comp_status"=>$comp_status,"cust_creator_id"=>$this->session->userdata('uId'),"array_uId"=>$array_parent_id));
			// echo $this->db->last_query();
			//}		
			
		}
		
		//$this->load->view('companies', $this->data);
        $this->load->view('qt/companies_list', $this->data);
	}


	public function detail(){		
		if(isset($_REQUEST['id'])&&$_REQUEST['id']!=""){
			$mod = @$_REQUEST["mod"];
			if($mod=="verify"){
				$this->model_companies->update(array("comp_status"=>1),$_REQUEST["id"]);
			}
		
			//$user_info =  $this->session->userdata('user_info');

			$array_parent_id = $this->session->userdata('parentId');
			
			$per = $this->session->userdata('user_info');
			$my_permisstion = $per["permission_apps"]["AM_SALE_SUPPORT"];			
			if(isset($my_permisstion["user_type"]["is_account"])){
				$array_parent_id=array();
			}
			
		
			$comp_id = $_REQUEST['id'];
			$result_comp = $this->model_companies->selectDetail(array("cust_creator_id"=>$this->session->userdata('uId'),"array_uId"=>$array_parent_id,'comp_id'=>$comp_id));
		
			//print_r($result_comp);
			$this->data["array_parent_id"]=$array_parent_id;
			if(count($result_comp)>0){
				$this->data["result"]=$result_comp[0];
			}
			


			$result = $this->model_customer->selectToCompID(array("cust_creator_id"=>$this->session->userdata('uId'),"array_uId"=>$array_parent_id,'comp_id'=>$comp_id));
			//$result = $this->model_customer->select(array('join_tbl_cust_users'=>'','uId'=>$this->session->userdata('uId'),"comp_id"=>$comp_id));
			//echo $this->db->last_query();
			$this->data["result_cust"]=$result;

			if(count($result_comp)>0){
				if(isset($my_permisstion["companies"])){
					foreach($my_permisstion["companies"] as $keys =>$val){		
						if(strlen($keys)>4&&substr($keys,0,4)=="hide"){
							//echo str_replace("hide","",$keys);
							//if(trim($this->data["result"][$vl])!=""){
								$this->data["result"][str_replace("hide_","",$keys)]="********";
								//$this->data["result"][$vl] = $this->fclass->subStringVN($this->data["result"][$vl],4)."...........";
						//	}				
						}				
					}
				}
                $this->load->view('qt/companies_detail1', $this->data);
			}else{
				$this->load->view('404');
			}			
		}else{
			$this->load->view('404');
		}
		
	}

	public function insert(){
		if($_SERVER['REQUEST_METHOD'] == 'POST'){
			$array=array();

			if(trim($_POST["cust_last_name"])==""||trim($_POST["cust_phone"])==""||trim($_POST["cust_email"])==""){
				$array=array("st"=>0,"msg"=>"Vui lòng nhập đầy đủ thông tin");
			}else{				

				$result=$this->model_customer->checkExists(
					array(	'cust_email'	=>$_POST["cust_email"],
						'cust_cmnd'			=>$_POST["cust_cmnd"],
						'cust_phone'		=>$_POST["cust_phone"],
						'cust_tax_code'		=>$_POST["cust_tax_code"],
						"cust_creator_id"	=>$this->session->userdata('uId')
						)
					);

				if(count($result)>0){
					$array=array("st"=>-1,"msg"=>"Khách hàng cá nhân này đã tồn tại trong danh sách khách hàng của bạn");
				}else{
					$result = $this->model_customer->checkExists(array('cust_cmnd'=>$_POST["cust_cmnd"],'cust_email'=>$_POST["cust_email"],'cust_phone'=>$_POST["cust_phone"],'cust_tax_code'=>$_POST["cust_tax_code"]));		
					$result_comp = $this->model_companies->checkExists(array('comp_phone'=>$_POST["comp_phone"],'comp_tax_code'=>$_POST["comp_tax_code"]));		
					if($_POST["cust_dob"]==""){
						$_POST["cust_dob"]=date('d-m-Y',time());
					}

					$id_conflict = $this->idConflict($result);

					$arrayCust=array(
						'cust_tax_code'		=>$_POST["cust_tax_code"],
						'cust_name'			=>'',
						'cust_first_name'	=>$_POST["cust_first_name"],
						'cust_last_name'	=>$_POST["cust_last_name"],
						'cust_address'		=>$_POST["cust_address"],
						'cust_phone'		=>$_POST["cust_phone"],
						'cust_email'		=>$_POST["cust_email"],
						'cust_cmnd'			=>$_POST["cust_cmnd"],
						'cust_cmnd_date'	=>$_POST["cust_cmnd_date"],
						'cust_sex'			=>$_POST["cust_sex"],
						'cust_bank_account'	=>$_POST["cust_bank_account"],
						'cust_status'		=>0,
						'cust_creator_id'	=>$this->session->userdata('uId'),
						'cust_create_time'	=>time(),
						'cust_dob'			=>$_POST["cust_dob"]
						//,
					//	'line_id'			=> json_encode($_POST["finance_lines"])
						);

					$arrayComp=array(
						'comp_name'			=>$_POST["comp_name"],
						'comp_address'		=>$_POST["comp_address"],
						'comp_phone'		=>$_POST["comp_phone"],
						'comp_ceo_name'		=>'',
						'comp_tax_code'		=>$_POST["comp_tax_code"],
						'comp_bank_account'	=>$_POST["comp_bank_account"],
						'comp_create_time'	=>time(),
						'comp_status'		=>0,
						'comp_type'			=>1
						);

					$cust_id=$this->model_customer->insert(array("arrayCust"=>$arrayCust));
					$comp_id=$this->model_companies->insert(array("arrayComp"=>$arrayComp));

					$this->model_customer->insertCustUser(array("cust_id"=>$cust_id,"uId"=>$this->session->userdata('uId')));
					$this->model_customer->insertCompCust(array("cust_id"=>$cust_id,"comp_id"=>$comp_id));

					if(count($result_comp)>0){
						if($id_conflict!=""){
							//$this->model_customer->updateCustUser(array("status"=>0),$custUserId);
							$this->model_customer->update(array("cust_status"=>-2,"cust_conflict_id"=>$id_conflict),$cust_id);
						}					

						$this->model_companies->update(array("comp_status"=>-2,"comp_conflict_id"=>$result_comp["comp_id"]),$comp_id);
						$array = array("st"=>0,"msg"=>"Thêm thành công (Doanh nghiệp đã tồn tại trong hệ thống. Vui lòng liên hệ kế toán để giải quyết)");
					}else if(count($result)>0){
						
					
						if($id_conflict!=""){
						//	$this->model_customer->updateCustUser(array("status"=>0),$custUserId);
							$this->model_customer->update(array("cust_status"=>-2,"cust_conflict_id"=>$id_conflict),$cust_id);
							$array = array("st"=>0,"msg"=>"Thêm thành công (Người dùng này đã có trong hệ thống, vui lòng liên hệ supper sale giải quyết)");
						}else{
							$array=array("st"=>1,"msg"=>"Thêm thành công","cust_id"=>$cust_id,"comp_id"=>$comp_id);
						}
					}else{
						$array = array("st"=>1,"msg"=>"Thêm thành công","cust_id"=>$cust_id,"comp_id"=>$comp_id);
					}
				}

			}
			echo json_encode($array);
		}
	}

	public function idConflict($result){
		//print_r($result);
		if(count($result)>0){
			foreach ($result as $key => $value) {
				$rows =	$this->model_customer->selectIdConflict(array("cust_id"=>$value["cust_conflict_id"]));
				if(count($rows)>0){
					if(trim($rows[0]["cust_conflict_id"])==""){
						return $rows[0]["cust_id"];
						break;
					}else{
						$this->idConflict($rows);
					}
				}else{
					return $value["cust_id"];
					break;
				}
			}	
		}else{
			return "";
		}
		
	}

	public function update(){
		$name_col	= $_REQUEST["name"];
		$value		= $_REQUEST["value"];
		$id			= $_REQUEST["id"];
		if(trim($name_col)==""){
			echo json_encode(array("result"=>false,"msg"=>"HACKING ERROR"));
		}else if(trim($value)==""){
			echo json_encode(array("result"=>false,"msg"=>"Vui lòng nhập nội dung"));
		}else if(trim($id)==""){
			echo json_encode(array("result"=>false,"msg"=>"Không tìm thấy ID"));
		}else{
			$this->model_companies->update(array($name_col=>$value,'comp_status'=>0),$id);
			echo json_encode(array("result"=>true,"msg"=>$value));
		}
	}
	
	public function remove_comp(){
		$comp_id = $_REQUEST["comp_id"];
		if(trim($comp_id)!=""){
			$result = $this->model_companies->selectIDDetail(array("comp_id"=>$comp_id));
			$this->model_companies->updateCompCust(array('comp_id'=>$result["comp_conflict_id"]),$comp_id);
			$this->model_companies->delete(array('comp_id'=>$comp_id));
			echo json_encode(array("result"=>true,"msg"=>"Xóa thành công. Đã chuyển khách hàng đến công ty mới","cust_id"=>$result["comp_conflict_id"]));
		}else{
			echo json_encode(array("result"=>false,"msg"=>"Không tìm thấy công ty"));
		}
		
	}	


		public function keep_comp(){
		$comp_id = $_REQUEST["comp_id"];
		if(trim($comp_id)!=""){
			//$result = $this->model_companies->selectIDDetail(array("comp_id"=>$comp_id));
			//$this->model_companies->updateCompCust(array('comp_id'=>$result["comp_conflict_id"]),$comp_id);
			//$this->model_companies->delete(array('comp_id'=>$comp_id));
			$this->model_companies->update(array("comp_conflict_id"=>null,"comp_status"=>0),$comp_id);
			echo json_encode(array("result"=>true,"msg"=>"Đã hủy xung đột doanh nghiệp thành công","comp_id"=>$comp_id));
		}else{
			echo json_encode(array("result"=>false,"msg"=>"Không tìm thấy công ty"));
		}
		
	}	

	


	public function remove_img_verify(){
		if(isset($_REQUEST['id']) && isset($_REQUEST['key'])){
			$result = $this->model_companies->selectIDDetail(array("comp_id"=>$_REQUEST['id']));
			//$customer = mysql_fetch_assoc($result);
			$comp_images = json_decode($result['comp_img_verify'],true);
			unset($comp_images[$_REQUEST['key']]);

			$data = array();
			//$data['comp_id'] = $_REQUEST['id'];
			$data['comp_img_verify'] = json_encode($comp_images);

			$result = $this->model_companies->update($data,$_REQUEST['id']);

			echo json_encode(array('result' => true,"msg"=>"xóa hình thành công"));
		}
		else echo json_encode(array('result' => false,"msg"=>"xóa hình thất bại"));
	}

	public function remove_img_tax(){
		if(isset($_REQUEST['id']) && isset($_REQUEST['key'])){
			$result = $this->model_companies->selectIDDetail(array("comp_id"=>$_REQUEST['id']));
			//$customer = mysql_fetch_assoc($result);
			$comp_images = json_decode($result['comp_img_tax'],true);
			unset($comp_images[$_REQUEST['key']]);

			$data = array();
			//$data['comp_id'] = $_REQUEST['id'];
			$data['comp_img_tax'] = json_encode($comp_images);

			$result = $this->model_companies->update($data,$_REQUEST['id']);

			echo json_encode(array('result' => true,"msg"=>"xóa hình thành công"));
		}
		else echo json_encode(array('result' => false,"msg"=>"xóa hình thất bại"));
	}
}

